package beer.coder.walawala.gui.handler;

import javafx.event.EventHandler;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;

/**
 * 窗口可拖拽.
 *
 * @author amath0312
 * @version 1.0
 * @date 2019-10-25 00:08
 */
public class MoveWindowHandler implements EventHandler<MouseEvent> {

  protected Stage stage;
  boolean isDragging = false;
  double sourceX;
  double sourceY;

  public MoveWindowHandler(Stage stage) {
    this.stage = stage;
    this.isDragging = false;
  }

  @Override
  public void handle(MouseEvent event) {
    if (event.getEventType() == MouseEvent.MOUSE_PRESSED
        && event.getButton() == MouseButton.PRIMARY) {
      isDragging = true;
      sourceX = event.getScreenX();
      sourceY = event.getScreenY();
    } else if (event.getEventType() == MouseEvent.MOUSE_DRAGGED) {
      if (isDragging) {
        double dx = event.getScreenX() - sourceX;
        double dy = event.getScreenY() - sourceY;
        stage.setX(stage.getX() + dx);
        stage.setY(stage.getY() + dy);
        sourceX = event.getScreenX();
        sourceY = event.getScreenY();
      }
    } else if (event.getEventType() == MouseEvent.MOUSE_RELEASED) {
      isDragging = false;
      sourceX = -1;
      sourceY = -1;
    }
  }
}
